<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室"></cp-nav-bar>
    <RoomStatus :status="consult?.status" :coundown="consult?.countdown"></RoomStatus>
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <RoomMessage v-for="item in list" :key="item.id" :item="item"></RoomMessage>
    </van-pull-refresh>

    <RoomAction
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="onSendText"
      @send-image="onSendImage"
    ></RoomAction>
  </div>
</template>

<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { io, Socket } from 'socket.io-client'
import { nextTick, onMounted, onUnmounted, provide, ref } from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType, OrderType } from '@/enums'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'

const store = useUserStore()
const route = useRoute()
const list = ref<Message[]>([])
//初始化信息标识
const initMsg = ref(true)
//订单数据
const consult = ref<ConsultOrderItem>()
const loadConsult = async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
}
//socket中获取此类型提示
let socket: Socket
onMounted(() => {
  loadConsult()
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`,
    },
    query: {
      orderId: route.query.orderId,
    },
  })
  socket.on('connect', () => {
    console.log('连接成功')
  })
  socket.on('disconnect', () => {
    console.log('链接关闭')
  })
  socket.on('error', () => {
    console.log('发生错误')
  })
  //获取聊天记录，建立连接后服务端会主动发给自己，默认传最新的时间到上一个时间的消息
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // console.log('聊天记录', data)
    const arr: Message[] = []
    data.forEach((item, index) => {
      if (index === 0) time.value = item.createTime
      arr.push({
        msgType: MsgType.Notify,
        msg: {
          content: item.createTime,
        },
        createTime: item.createTime,
        id: item.createTime,
      })
      arr.push(...item.items)
    })
    list.value.unshift(...arr)
    loading.value = false
    if (!arr.length) return showToast('没有更多聊天记录')
    //默认看到最新消息
    if (initMsg.value) {
      socket.emit('updateMsgStatus', arr[arr.length - 1].id)
      nextTick(() => {
        window.scrollTo(0, document.body.scrollHeight)
        initMsg.value = false
      })
    }
  })
  // 监听状态改变
  socket.on('statusChange', () => {
    loadConsult()
  })
  //监听发送、接收的消息
  socket.on('receiveChatMsg', async (event) => {
    // console.log(event)
    socket.emit('updateMsgStatus', event.id)
    list.value.push(event)
    // 获取更新后的 DOM
    await nextTick()
    window.scrollTo(0, document.body.scrollHeight)
  })
})
onUnmounted(() => {
  socket.close()
})
// 发送文本信息
const onSendText = (text: string) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: { content: text },
  })
}
// 发送图片信息
const onSendImage = (image: Image) => {
  // console.log(image)
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: { picture: image },
  })
}
// 下拉刷新
const loading = ref(false)
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const onRefresh = () => {
  socket.emit('getChatMsgList', 20, time.value, consult.value?.id)
}
//像评价组件传递id，这里传consult不传.value,因为要响应式的数据
provide('consult', consult)
// 修改评价信息，遵循信息从哪来修改哪里的
const completeEva = (score: number) => {
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  //这里接口不提供websocket，用传统的方式修改可视化数据
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
provide('completeEva', completeEva)
</script>

<style scoped lang="scss">
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
